let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
let moment = require("moment");
let constants = require("../utils/constants");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = constants.USER_CONFIG_TABLE;
const tableConfigName = "SAP_JIANGDU_VIP_TICKET_CONFIG";
const ohana_instance = new ohana(tableName);
const ohana_instance_config = new ohana(tableConfigName);
const ohana_instance_user = new ohana(constants.REGISTEDUSERSTABLE);
const ohana_instance_vip = new ohana(constants.VIPUSERSCORE);
const ohana_instance_ticket_log = new ohana(constants.VIPTICKETLOG);

const { checkAuth } = require("../utils/utils");

router.post("/consumeTicket", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '消耗赋能券'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    //check user id from jwt token
    // update ticket log
    // update vip user score 中的tickets
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }
    const { data } = req.body;
    //check if enough tickets.
    const payload = {
        USER_ID: user.user_id,
        consumeTicket: data.TICKET,
        service: data.AUTH,
    };
    checkEnoughTicket(payload).then((result) => {
        if (result.code == 0) {
            addTicketLog(payload);
            res.status(200).send(result);
        } else {
            res.status(400).send(result);
        }
    });
});
async function addTicketLog(payload) {
    const result = await ohana_instance_ticket_log.insert({
        USER_ID: payload.USER_ID,
        TICKET_LOG: payload.consumeTicket,
        DATE: moment().format("YYYY-MM-DD HH:mm:ss"),
        AUTH: payload.service,
    });
    return result;
}
async function checkEnoughTicket(payload) {
    var result = await ohana_instance_vip.find(["TICKETS"], {
        USER_ID: payload.USER_ID,
    });
    let resultJson = {};
    if (result.length > 0) {
        console.log(result[0].TICKETS);
        if (result[0].TICKETS > payload.consumeTicket) {
            //update
            let updateResult = await ohana_instance_vip.update(
                { USER_ID: payload.USER_ID },
                { TICKETS: result[0].TICKETS - payload.consumeTicket }
            );
            console.log(updateResult);
            updateResult = await ohana_instance.update(
                { USER_ID: payload.USER_ID, AUTH: payload.service },
                { STATUS: true }
            );
            console.log(updateResult);
            if (updateResult == 1) {
                resultJson = { message: "开通成功", code: 0 };
            } else {
                resultJson = { message: "开通失败", code: -1 };
            }
        } else {
            resultJson = { message: "赋能券不够,开通失败", code: -1, cause: "" };
        }
    }
    return resultJson;
}

router.get("/getParameters", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '获取赋能券配置'
    // #swagger.description = '不需要JWT Token'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    getTicketParameters().then((result) => {
        res.status(200).send(result);
    });
});
async function getTicketParameters() {
    var result = await ohana_instance_config.find();
    return result;
}

router.get("/", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '获取方块'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    payload.USER_ID = user.user_id;
    let { TYPE } = req.query;
    if (TYPE) {
        payload.TYPE = TYPE;
    }

    getData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/initConfig", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '根据user表 初始化单个用户方块'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let USER_ID = user.user_id;
    let { USER_ID_QUERY } = req.query;
    if (USER_ID_QUERY) {
        USER_ID = USER_ID_QUERY
    }

    let payload = {};
    payload.USER_ID = USER_ID;

    insertConfigData(payload)
        .then(() => {
            res.sendStatus(200);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});
router.get("/reInitConfig", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '根据user表 更新单个用户方块'
    // #swagger.description = '需要JWT Token 传入data:{user: }'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let { USER_ID } = req.query;
    let payload = {};
    payload.USER_ID = USER_ID;

    deleteSingleUserData(USER_ID)
        .then(() => {
            insertConfigData(payload);
            res.sendStatus(200);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});
async function updateAlreadyData() {
    const allActivatedServices = await ohana_instance_ticket_log.find();
    allActivatedServices.map((one) => {
        ohana_instance.update(
            { USER_ID: one.USER_ID, AUTH: one.AUTH },
            { STATUS: true }
        );
    });
}
router.put("/updateStatus", function (req, res, next) {
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }
    const { data } = req.body;
    updateUserConfig(data).then(result => {
        if (result > 0) {
            res.sendStatus(200);
        } else {
            res.sendStatus(400);
        }

    })
});
router.post("/", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '控制方块显示/隐藏'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    /*  #swagger.requestBody = {
                    required: true,
                    content: {
                        "application/json": {
                            schema: {
                                $ref: "#/definitions/userConfig_add"
                            }  
                        },
                    }
            } */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let { data } = req.body;

    updateData(data)
        .then(() => {
            res.sendStatus(200);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/go", function (req, res, next) {
    // #swagger.tags = ['用户权限配置']
    // #swagger.summary = '根据user表 更新所有账户的方块'
    // #swagger.description = '不需要JWT Token'
    /* #swagger.security = [{
                     "JiangduJWT": []
        }] */
    deleteAllData()
        .then(() => {
            //更新全部数据
            insertConfigData()
                .then(() => {
                    updateAlreadyData();
                    res.sendStatus(200);
                })
                .catch((err) => {
                    log.error(err);
                    res.status(500).send(err);
                });
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

//有userID就只更新一个，没有userID就全部更新
async function insertConfigData(userPayload) {
    getUserData(userPayload).then((userResult) => {
        // 遍历User
        log.info(userResult);
        userResult.forEach((element) => {
            //有哪些权限
            let auths = [];
            if (element.LEVEL == "L2") {
                auths = JSON.parse(element.AUTH);
            } else {
                auths = ["POC", "PUB", "RE", "CO", "CA", "RPA", "SAC", "SUP", "WT"];

            }
            // 遍历权限
            log.info(auths);
            for (let i = 0; i < auths.length; i++) {
                let auth = auths[i];
                let data = {};
                data.USER_ID = element.USER_ID;
                data.CREATED_AT = moment(new Date()).format("YYYY-MM-DD HH");
                let backgrounds = [
                    "#4a90e2",
                    "#5a9fe7",
                    "#74b8ef",
                    "#74b8ef",
                    "#2196F3",
                    "#64B5F6",
                    "#64B5F6",
                ];
                let randomNum = Math.round(Math.random() * 6);
                data.BACKGROUND = backgrounds[randomNum];
                if (auth == "PUB") {
                    data.AUTH = "PUB";
                    data.STATUS = true;
                    data.NAME = "微发布";
                    data.DESCRIPTION = "企业发布资源共享：精英人才、优质设备、科创技术。";
                    data.ICON = "mdi-calendar-edit";
                    data.URL = "/index/myapp/publish";
                    data.TYPE = "page";
                } else if (auth == "SUP") {
                    data.AUTH = "SUP";
                    data.STATUS = false;
                    data.NAME = "SAP小微企业进销存";
                    data.DESCRIPTION = "适用小微企业的简易进销存套件。";
                    data.ICON = "mdi-infinity";
                    data.TYPE = "window";
                } else if (auth == "POC") {
                    data.AUTH = "POC";
                    data.STATUS = true;
                    data.NAME = "企业数字化体检";
                    data.DESCRIPTION = "智能匹配企业适合的奖补政策、金融产品、精英人才、优质设备、科创技术，自动生成企业数字体检评估报告。";
                    data.ICON = "mdi-clipboard-check";
                    data.URL = "/index/policyCalculator";
                    data.TYPE = "page";
                } else if (auth == "RE") {
                    data.AUTH = "RE";
                    data.STATUS = true;
                    data.NAME = "微需求";
                    data.DESCRIPTION =
                        "企业提出资源需求：金融产品、精英人才、优质设备、科创技术。";
                    data.ICON = "mdi-message-bulleted";
                    data.URL = "/index/myapp/microRequire";
                    data.TYPE = "page";
                } else if (auth == "CO") {
                    data.AUTH = "CO";
                    data.STATUS = false;
                    data.NAME = "微协同";
                    data.DESCRIPTION = "满足供应链上下游供货需求对接。";
                    data.ICON = "mdi-source-merge";
                    data.URL = "/index/myapp/collaboration";
                    data.TYPE = "page";
                } else if (auth == "CA") {
                    data.AUTH = "CA";
                    data.STATUS = false;
                    data.NAME = "微分析";
                    data.DESCRIPTION = "对供应链上下游供货需求的图表分析。";
                    data.ICON = "mdi-chart-box-outline";
                    data.URL = "/index/myapp/codashboard";
                    data.TYPE = "page";
                } else if (auth == "WT") {
                    data.AUTH = "WT";
                    data.STATUS = false;
                    data.NAME = "微记事";
                    data.DESCRIPTION = "企业待办事项记录与提醒。";
                    data.ICON = "mdi-clock-outline";
                    data.URL = "/index/myapp/worktable";
                    data.TYPE = "page";
                } else if (auth == "GRAPH") {
                    data.AUTH = "GRAPH";
                    data.STATUS = true;
                    data.NAME = "拓扑图";
                    data.DESCRIPTION =
                        "企业拓扑图服务提供交互式可视化企业关系网络图，帮助企业更直观地分析存在业务往来的合作伙伴及其上下游企业关系拓扑结构。";
                    data.ICON = "mdi-graph";
                    data.URL = "/index/myapp/network";
                    data.TYPE = "page";
                } else if (auth == "RPA") {
                    data.AUTH = "RPA";
                    data.STATUS = false;
                    data.NAME = "SAP业务流程自动化机器人";
                    data.DESCRIPTION = "自动化重复性业务操作。";
                    data.ICON = "mdi-robot";
                    // data.URL = "https://yangzhou-jiangdu-big.cn40.analytics.sapcloud.cn/sap/fpa/ui/app.html#/story&/s/D138130737C71405097223F358DBAB83/?mode=view"
                    data.TYPE = "window";
                } else if (auth == "SAC") {
                    data.AUTH = "SAC";
                    data.STATUS = false;
                    data.NAME = "SAP经营数据分析云";
                    data.DESCRIPTION = "可视化经营数据图表。";
                    data.ICON = "mdi-chart-bar-stacked";
                    // data.URL = "https://yangzhou-jiangdu-big.cn40.analytics.sapcloud.cn/sap/fpa/ui/app.html#/story&/s/D138130737C71405097223F358DBAB83/?mode=view"
                    data.TYPE = "window";
                } else if (auth == "JB") {
                    data.AUTH = "JB";
                    data.STATUS = false;
                    data.NAME = "奖补平台";
                    data.DESCRIPTION = "奖补平台";
                    data.ICON = "mdi-alpha-f-circle-outline";
                    data.URL = "https://sqjbzj.jiangdu.gov.cn/";
                    data.TYPE = "window";
                } else if (auth == "GOV") {
                    data.AUTH = "GOV";
                    data.STATUS = false;
                    data.NAME = "江都市政府";
                    data.DESCRIPTION = "江都市政府";
                    data.ICON = "mdi-city-variant-outline";
                    data.URL = "http://www.jiangdu.gov.cn/";
                    data.TYPE = "window";
                }
                if (element.LEVEL == "L2") {
                    data.STATUS = true;
                }
                if (data.AUTH) {
                    insertData(data)
                        .then(() => {
                            log.info(data);
                        })
                        .catch((err) => {
                            log.error(err);
                        });
                }
            }
        });
        return userResult.length;
    });
}

async function updateUserConfig(payload) {
    console.log(payload);
    let result = await ohana_instance.update({ USER_ID: payload.USER_ID }, { STATUS: payload.STATUS });
    return result;

}

async function getUserData(payload) {
    let result = await ohana_instance_user.find(payload);
    return result;
}

async function getData(condition) {
    let result = [];
    result = await ohana_instance.find(condition);
    return result;
}

async function updateData(data) {
    for (let index = 0; index < data.length; index++) {
        await ohana_instance.update(
            {
                TAG_ID: data[index].TAG_ID,
            },
            data[index]
        );
    }
}

async function insertData(data) {
    data.TAG_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);
    return result;
}

async function deleteSingleUserData(USER_ID) {
    let result = ohana_instance.raw(
        'delete from "' + tableName + "\" where USER_ID = '" + USER_ID + "'"
    );
    return result;
}

async function deleteAllData() {
    let result = ohana_instance.raw('delete from "' + tableName + '"');
    return result;
}

module.exports = router;
